#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Author:Leon

import configparser
import psycopg2

import sys
from urllib import request
import json
import requests
import os

table = "ads_zkd_izone_customized_api"
group_id="bgy"
group_name="碧桂园"
project_id="bgylxy"
project_name="碧桂园漓湘悦"

url='http://125.91.34.11:8124/app/intelligent/izone/getIZoneBasicPortraitData?pid=P_20190410101058110&aid=A_000000IN02347c5f77ae414b9b9fe2feeaed73af&year=2019'
api_name='getIZoneBasicPortraitData'

cf = configparser.ConfigParser()
cf.read("/git/datawarehouse/conf/etl/database.cfg")
# 数据库连接配置读取
DATABASE = cf.get("edw", "database")
USERNAME = cf.get("edw", "username")
PASSWORD = cf.get("edw", "password")
HOST = cf.get("edw", "host")
PORT = cf.get("edw", "port")

conn = psycopg2.connect(database=DATABASE, user=USERNAME, password=PASSWORD, host=HOST, port=PORT)
cur = conn.cursor()

def insert_db(api_name,data):
    try:
        data_tuple=(api_name,json.dumps(data,ensure_ascii=False),group_id,group_name,project_id,project_name)

        sqlstr = "delete from "+ table + " where group_id='"+group_id+"' and project_id='"+project_id+"' and api_name='"+api_name+"'"
        cur.execute(sqlstr)
        sqlstr = "insert into " + table + " (api_name,api_data,group_id,group_name,project_id,project_name) values (%s,%s,%s,%s,%s,%s) "
        cur.execute(sqlstr,data_tuple)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print('数据库处理异常', e)
        traceback.print_exc()


def get_api_data(url):
    data = None
    rq = request.Request(url, data = data)
    res = request.urlopen(rq)
    respoen = res.read()
    result = str(respoen, encoding = "utf-8")
    # print(type(result))
    return json.loads(result)

def get_input(api_name,url):
    api_data=get_api_data(url)
    if api_data['result']['code']=='2000':
        print('success')
        insert_db(api_name,api_data)

#if __name__ == '__main__':
get_input(api_name,url)










